//
//  POI.m
//  WeddingStoreFinder
//
//  Created by Macdev on 11/19/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "POI.h"
#import "Dress.h"
#import "AppDelegate.h"

@interface POI()




+ (void) savePOI:(NSDictionary*)poiDict;
+ (void) updatePOI:(POI*)poi withPoiDict:(NSDictionary*)poiDict;


- (void) deletePOI;

@end


@implementation POI

@dynamic customPoiId;
@dynamic longitude;
@dynamic latitude;
@dynamic address;
@dynamic city;
@dynamic phone;
@dynamic poiName;
@dynamic zipCode;
@dynamic dresses;
@dynamic poiStatus;

@synthesize distanceFromLocation;


+ (void) processPOIList:(id)JSONResult {
	@synchronized ([UIApplication sharedApplication]) {
		//NSLog(@"processPOIList START");
		if ([JSONResult isKindOfClass:[NSDictionary class]]) {
			AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
			NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
			NSArray *poiArray = [JSONResult valueForKey:kJSON_response];
			for (NSDictionary *poiDict in poiArray) {
				POI *poiToUpdate = [POI getPOIByCustomId:[[poiDict valueForKey:kJSON_id] intValue]];
				if (poiToUpdate) {
					
					[POI updatePOI:poiToUpdate withPoiDict:poiDict];
					
					
				} else {
					if ([[poiDict valueForKey:kJSON_status] intValue] != kPOIStatus_toDelete) {
						[POI savePOI:poiDict];
					}
				}
				
			}
			// Commit the change.
			NSError *error;
			if (![managedObjectContext save:&error]) {
				NSLog(@"Exception(POI-processPOIList): %@", [error description]);
			}
			
			//delete POIs with toDelete status:
			NSArray *poisToDelete = [POI getPOIsByStatus:kPOIStatus_toDelete];
			for (POI *poiToDelete in poisToDelete) {
				[poiToDelete deletePOI];
			}
			
			//NSLog(@"processPOIList END");	
		} else {
			//NSLog(@"processPOIList END");	
			return;
		}
	}
}

+ (POI*) getPOIByCustomId:(int)_customPOIId {
	AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
	NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
	
	// Create the fetch request for the entity.
	NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
	// Edit the entity name as appropriate.
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"POI" inManagedObjectContext:managedObjectContext];
	[fetchRequest setEntity:entity];
	
	// Set the batch size to a suitable number.
	[fetchRequest setFetchBatchSize:20];
	
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"customPoiId == %d", _customPOIId];
	[fetchRequest setPredicate:predicate];
	
	// Edit the section name key path and cache name if appropriate.
	// nil for section name key path means "no sections".
	NSError *error = nil;
	NSArray *poisToReturn = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
	
	[fetchRequest release];
	if (error) {
		NSLog(@"POI - getPOIByCustomId - %@", [error localizedDescription]);
	}
	if ([poisToReturn count] > 0) {
		POI *retValue = [poisToReturn objectAtIndex:0];
		return retValue;
	} else {
		return nil;
	}
}

+ (NSArray*) getPOIsByStatus:(int)_status {
	AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
	NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
	
	// Create the fetch request for the entity.
	NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
	// Edit the entity name as appropriate.
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"POI" inManagedObjectContext:managedObjectContext];
	[fetchRequest setEntity:entity];
	
	// Set the batch size to a suitable number.
	[fetchRequest setFetchBatchSize:20];
	
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"poiStatus == %d", _status];
	[fetchRequest setPredicate:predicate];
	
	// Edit the section name key path and cache name if appropriate.
	// nil for section name key path means "no sections".
	NSError *error = nil;
	NSArray *poisToReturn = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
	
	[fetchRequest release];
	if (error) {
		NSLog(@"POI - getPOIByCustomId - %@", [error localizedDescription]);
	}
	if ([poisToReturn count] > 0) {
		return poisToReturn;
	} else {
		return nil;
	}
}

+ (void) savePOI:(NSDictionary*)poiDict {
	AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
	NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
	POI *poi = (POI *)[NSEntityDescription insertNewObjectForEntityForName:@"POI" inManagedObjectContext:managedObjectContext];
	[POI updatePOI:poi withPoiDict:poiDict];
}

+ (void) updatePOI:(POI*)poi withPoiDict:(NSDictionary*)poiDict {
	
	poi.customPoiId = (NSNumber*)[poiDict valueForKey:kJSON_id];
	poi.longitude = (NSNumber*)[poiDict valueForKey:kJSON_longitude];
	poi.latitude = (NSNumber*)[poiDict valueForKey:kJSON_latitude];
	poi.poiStatus = (NSNumber*)[poiDict valueForKey:kJSON_status];
	poi.address = [poiDict valueForKey:kJSON_address];
	poi.phone = [poiDict valueForKey:kJSON_phone];
	poi.poiName = [poiDict valueForKey:kJSON_name];
	poi.city = [poiDict valueForKey:kJSON_city];
	poi.zipCode = [poiDict valueForKey:kJSON_zipcode];
	
}

+ (NSArray*) getPOIListOrderBy:(NSString*)orderBY {
	NSArray *retValue;
	AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
	NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
	[managedObjectContext deletedObjects];
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"POI" inManagedObjectContext:managedObjectContext];
	[request setEntity:entity];
	if (!orderBY) {
		orderBY = @"poiName";
	}
	NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:orderBY ascending:YES];
	NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
	[request setSortDescriptors:sortDescriptors];
	[sortDescriptor release];
	[sortDescriptors release];
	
	NSError *error = nil;
	retValue = [managedObjectContext executeFetchRequest:request error:&error];
	[request release];
	if (error) {
		NSLog(@"Exception(POI-deleteAll): %@", [error description]);
	}
	return retValue;
}

#pragma mark -
#pragma mark indstance methods

- (void) deletePOI {
	AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
	NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
	[managedObjectContext deleteObject:self];
	for (Dress *dress in self.dresses) {
		
		[managedObjectContext deleteObject:dress];
	}
	NSError *error;
	if (![managedObjectContext save:&error]) {
		NSLog(@"Exception(POI-delete): %@", [error description]);
	}
}

#pragma mark - MKAnnotation

- (NSString *)title {
    return self.poiName;
}

- (NSString *)subtitle {
    return self.address;
}

- (CLLocationCoordinate2D)coordinate {
    CLLocationCoordinate2D theCoordinate;
    theCoordinate.latitude = [self.latitude floatValue];
    theCoordinate.longitude = [self.longitude floatValue];
    return theCoordinate; 
}

@end
